package com.gticket.customerbackend.dlx;

import com.gticket.customerbackend.mapper.MovieScheduleMapper;
import com.gticket.customerbackend.pojo.CinemaCode;
import com.gticket.customerbackend.util.RabbitUtils;
import com.rabbitmq.client.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;

/**
 * @author 李浩楠
 * @date 2019/11/25 下午4:19
 */
public class DlxConsumer {
    private final static String exchangeName = "direct-exchange";
    private final static String routingKey = "schedule";// routekey

    @Autowired
    private static MovieScheduleMapper movieScheduleService;
    //private static Orders orders = null;

    private static final Logger log = LoggerFactory.getLogger(DlxConsumer.class);

    public static void dataupdate()throws Exception {
        Connection connection = RabbitUtils.getConnection();
        Channel channel = connection.createChannel();
        boolean autoAck = false;
        DefaultConsumer callbackConsumer =  new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                                       byte[] body) throws IOException {
                try {
                    //TimeUnit.SECONDS.sleep(2);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                String routingKey = envelope.getRoutingKey();
                long deliveryTag = envelope.getDeliveryTag(); // channel.basicAck(deliveryTag, false);
                log.info("消息的路由键：" + routingKey);
                log.info("消息标签：" + deliveryTag);
                log.info("消息内容：" + new String(body, "UTF-8"));
                //将字节数组body转为string   截取拿到 数据
                String[] message = new String(body).split(",");
                String db = message[0];
                //封装对象
                CinemaCode cinemaCode = new CinemaCode();
                cinemaCode.setDb(db);
                int fs_id = Integer.valueOf(message[1]);
                // 根据信息直接修改表的flag
                movieScheduleService.updateMovieScheduleFlag(cinemaCode,fs_id);
                channel.basicAck(deliveryTag, false);
            }
        };

        channel.basicConsume("dlx_queue1", autoAck, "", callbackConsumer);
        channel.close();
        connection.close();
    }
}
